set -eo pipefail

# ================= 配置区 =================
PROJECT_ROOT="$(cd "$(dirname "$0")"; pwd)"
FRONTEND_DIR="${PROJECT_ROOT}/frontend/forum/src"
BACKEND_DIR="${PROJECT_ROOT}/backend/src"
SUBMODULE_DIR="${PROJECT_ROOT}/backend/third"

# ================= 子模块克隆逻辑 =================

# 检查.gitmodules文件是否存在
if [ ! -f "${PROJECT_ROOT}/.gitmodules" ]; then
    echo "❌ 错误：未找到.gitmodules文件，请确认项目初始化完成"
    exit 1
fi

echo "🔍 正在解析.gitmodules中的子模块地址..."

# 提取所有子模块URL（兼容带空格的情况）
SUB_URLS=()
while IFS= read -r line; do
    SUB_URLS+=("$(echo "$line" | sed -E 's/.*=\s*//')")
done < <(grep -E '^\s*url\s*=' "${PROJECT_ROOT}/.gitmodules")

# 切换到子模块存放目录
echo "📁 进入子模块目录：${SUBMODULE_DIR}"
mkdir -p "${SUBMODULE_DIR}"
cd "${SUBMODULE_DIR}"

# 遍历克隆子模块
TOTAL=${#SUB_URLS[@]}
COUNTER=1
for URL in "${SUB_URLS[@]}"; do
    # 从URL中提取仓库名称（去除.git后缀）
    REPO_NAME=$(basename "${URL}" .git)
    TARGET_DIR="${SUBMODULE_DIR}/${REPO_NAME}"

    # 存在性检查逻辑
    if [ -d "${TARGET_DIR}" ]; then
        if [ -d "${TARGET_DIR}/.git" ]; then
            # 验证远程URL是否匹配
            CURRENT_URL=$(git -C "${TARGET_DIR}" config --get remote.origin.url)
            if [ "${CURRENT_URL}" = "${URL}" ]; then
                echo "✅ 子模块已存在且配置正确，跳过：${REPO_NAME} "
                ((COUNTER++))
                continue
            else
                echo "❌ 错误：子模块 ${REPO_NAME} 存在但远程URL不匹配（当前：${CURRENT_URL}）"
                exit 3
            fi
        fi
    fi

    # 执行克隆操作
    echo "🔄 正在克隆子模块 (${COUNTER}/${TOTAL}): ${URL}"
    if git clone "${URL}" "${TARGET_DIR}"; then
        echo "✅ 克隆成功：${REPO_NAME}"
    else
        echo "❌ 克隆失败: ${URL}"
        exit 3
    fi
    ((COUNTER++))
done

# 返回项目根目录
echo "🔙 返回项目根目录"
cd "${PROJECT_ROOT}"

echo "✅ 所有子模块克隆完成！"